package com.monitor.task;

import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import java.util.ResourceBundle;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.monitor.action.MonitorActionSupport;
import com.monitor.po.User;
import com.monitor.service.UserService;

public class TimerTask extends QuartzJobBean implements Serializable {

	private static final long serialVersionUID = -8206996626170821638L;
	private UserService userService;

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		try {
			Calendar calendar = Calendar.getInstance();
			int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
			// 凌晨时清除用户数据
			if (hourOfDay == 0) {
				userService.clearData();
			}
			// 删除上时间未与服务器通讯的用户
			long period = System.currentTimeMillis() - 5 * 60 * 60 * 1000;
			List<User> users = userService.getUserBySycTime(period);
			if (users != null && !users.isEmpty()) {
				String fileDir = getSaveDirName();
				for (User user : users) {
					userService.deleteUserById(user.getId(), fileDir);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取上传文件的目录
	 * 
	 * @return
	 */
	protected String getSaveDirName() {
		// 获取文件配置
		ResourceBundle rb = ResourceBundle.getBundle(MonitorActionSupport.FILE_CONFIG_NAME);
		// 获取文件上传保存路径配置
		return rb.getString(MonitorActionSupport.FILE_SAVE_DIR);
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
